﻿using System;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Controls;
using System.Windows.Printing;
using AdventureWorksLT.Core;
using AdventureWorksLT.Views.Customers.ChildWindows;
using AdventureWorksLT.Views.Customers.DesignerData;
using AdventureWorksLT.Views.Customers.Reports;
using AdventureWorksLT.Web.Models;
using AdventureWorksLT.Web.Services;
using System.Collections.ObjectModel;
using System.Windows;
using RelayCommand = AdventureWorksLT.Core.RelayCommand;

namespace AdventureWorksLT.Views.Customers.ViewModels
{
public class SalesOrderDetailsViewModel : PerformAsyncQueryBase // the AsyncQuery one inherits from ViewModel Base
{
public static AdventureWorksLTDomainContext SalesOrderDetailsContext;
private ObservableCollection<SalesOrderDetail> _salesOrderDetails;
private AdventureWorksLTDomainContext _context;
private EntityQuery<AdventureWorksLT.Web.Models.Product> _productQuery;
private int _pageIndex = 0;
//
    public SalesOrderDetailsViewModel()
        {
            if (!IsDesignTime)
            {
                SalesOrderDetailsContext = new AdventureWorksLTDomainContext();
            IsBusy = true;
            WireCommands();
            LoadSalesOrderDetailsAsync();
            LoadComboBoxData();
            }
                else
                {
                DesignTimeSalesOrderDetail _designTimeSalesOrderDetail = new DesignTimeSalesOrderDetail();
                SalesOrderDetailsCollection = new ObservableCollection<SalesOrderDetail>(_designTimeSalesOrderDetail.ToList());
                CurrentSalesOrderDetails = SalesOrderDetailsCollection.FirstOrDefault();
                }
        }
#region "Load Current SalesOrderDetails"
    readonly int SalesOrderHeaderID = AdventureWorksLT.Views.Customers.ViewModels.SalesOrderHeadersViewModel.DashLoad_PK;
    private void LoadSalesOrderDetailsAsync()
    {
        if (!SalesOrderDetailsContext.IsSubmitting)
        {
            if (SalesOrderHeaderID > 0)
        {
            PerformAsyncQuery<SalesOrderDetail>(SalesOrderDetailsContext, SalesOrderDetailsContext.GetSalesOrderDetailsForOrderQuery(SalesOrderHeaderID), SalesOrderDetailsLoadedComplete);
        }
        else
        {
            PerformAsyncQuery<SalesOrderDetail>(SalesOrderDetailsContext, SalesOrderDetailsContext.GetSalesOrderDetailsQuery(), SalesOrderDetailsLoadedComplete); 
        }
        }
    }
    private ObservableCollection<SalesOrderDetail> _salesOrderDetailsCollection;
    public ObservableCollection<SalesOrderDetail> SalesOrderDetailsCollection
        {
        get { return _salesOrderDetailsCollection; }
        set
            {
            _salesOrderDetailsCollection = value;
            RaisePropertyChanged("SalesOrderDetailsCollection");
            }
        }
        
    private SalesOrderDetail _currentSalesOrderDetails;
    public SalesOrderDetail CurrentSalesOrderDetails
        {
        get { return _currentSalesOrderDetails; }
        set
            {
            _currentSalesOrderDetails = value;
            RaisePropertyChanged("CurrentSalesOrderDetails");
            }
        }
#endregion "Load Current SalesOrderDetails"
#region Commands
    private void EnableCommands()
        {
        AddNewSalesOrderDetailsCommand.IsEnabled = true;
        EditCurrentInNewWindowCommand.IsEnabled = true;
        SaveSalesOrderDetailsCommand.IsEnabled = true;
        DeleteSalesOrderDetailsCommand.IsEnabled = true;
        PrintSalesOrderDetailsCommand.IsEnabled = true;
        SearchSalesOrderDetailsCommand.IsEnabled = true;
        EditCurrentInNewWindowCommand.IsEnabled = true;
        ShowChartDashboardCommand.IsEnabled = true;
        SelectionChangedSdkCommand.IsEnabled = true;
        RowLoadingSdkCommand.IsEnabled = true;
        PreviousPageCommand.IsEnabled = true;
        NextPageCommand.IsEnabled = true;
        }
    private void WireCommands()
        {
        AddNewSalesOrderDetailsCommand = new RelayCommand(AddSalesOrderDetails);
        EditCurrentInNewWindowCommand = new RelayCommand(EditCurrentInNewWindow);
        SaveSalesOrderDetailsCommand = new RelayCommand(SaveSalesOrderDetails);
        DeleteSalesOrderDetailsCommand = new RelayCommand(DeleteSalesOrderDetails);
        PrintSalesOrderDetailsCommand = new RelayCommand(PrintSalesOrderDetails);
        ShowChartDashboardCommand = new RelayCommand<object>(ShowChartDashboard);
        SearchSalesOrderDetailsCommand = new RelayCommand<string>(SearchInSalesOrderDetails);
            SelectionChangedSdkCommand = new RelayCommand<SalesOrderDetail>(OnExecuteSelectionChangedSDK);
            RowLoadingSdkCommand = new RelayCommand<System.Windows.Controls.DataGridRowEventArgs>(OnExecuteRowLoadingSDK);
            PreviousPageCommand = new RelayCommand(PreviousPage);
            NextPageCommand = new RelayCommand(NextPage);
        }



    private void OnExecuteRowLoadingSDK(System.Windows.Controls.DataGridRowEventArgs e)
        {
        AdventureWorksLT.Web.Models.SalesOrderDetail model = e.Row.DataContext as AdventureWorksLT.Web.Models.SalesOrderDetail;
        
        var grid = new Grid();
        var tb = new TextBlock
        {
        Text = string.Format(
			 "Sales Order Detail Id : {0} \r\n" +  "Order Qty : {1} \r\n" +  "Unit Price : {2} \r\n" +  "Unit Price Discount : {3} \r\n" +  "Line Total : {4} \r\n" +  "Rowguid : {5} \r\n" +  "Modified Date : {6} \r\n" , 
			 model.SalesOrderDetailID,  model.OrderQty,  model.UnitPrice,  model.UnitPriceDiscount,  model.LineTotal,  model.rowguid,  model.ModifiedDate  ),
Margin = new Thickness(3, 3, 3, 3),
Opacity = 0.8,
MaxWidth = 250,
FontSize = 10,
TextWrapping = TextWrapping.NoWrap
};
grid.Children.Add(tb);
ToolTipService.SetToolTip(e.Row, grid);
}
        private void OnExecuteSelectionChangedSDK(SalesOrderDetail CheckedSalesOrderDetails)
        {
                CurrentSalesOrderDetails = CheckedSalesOrderDetails;

                SelectedProduct =
                ProductCollection.Where(c => CurrentSalesOrderDetails != null && c.ProductID == CurrentSalesOrderDetails.ProductID).SingleOrDefault();
        }

        private void NextPage()
        {
            _pageIndex++;
            SalesOrderDetailsCollection = new ObservableCollection<SalesOrderDetail>(SalesOrderDetailsContext.SalesOrderDetails.Skip(_pageIndex * 20).Take(20));
            CurrentSalesOrderDetails = SalesOrderDetailsCollection.FirstOrDefault();
        }

        private void PreviousPage()
        {
            _pageIndex--;
            SalesOrderDetailsCollection = new ObservableCollection<SalesOrderDetail>(SalesOrderDetailsContext.SalesOrderDetails.Skip(_pageIndex * 20).Take(20));
            CurrentSalesOrderDetails = SalesOrderDetailsCollection.FirstOrDefault();
        }

        public RelayCommand<System.Windows.Controls.DataGridRowEventArgs> RowLoadingSdkCommand
        {
            get;
            private set;
        }
        public RelayCommand<SalesOrderDetail> SelectionChangedSdkCommand
        {
            get;
            private set;
        }
        public RelayCommand PreviousPageCommand
        {
            get;
            private set;
        }
        public RelayCommand NextPageCommand
        {
            get;
            private set;
        }

    public RelayCommand AddNewSalesOrderDetailsCommand
    {
    get;
    private set;
    }
    public RelayCommand EditCurrentInNewWindowCommand
    {
        get;
        private set;
    }
    public RelayCommand SaveSalesOrderDetailsCommand
    {
    get;
    private set;
    }
    public RelayCommand DeleteSalesOrderDetailsCommand
    {
    get;
    private set;
    }
    public RelayCommand PrintSalesOrderDetailsCommand
    {
    get;
    private set;
    }
    public RelayCommand<object> ShowChartDashboardCommand
    {
    get;
    private set;
    }
    public RelayCommand<string> SearchSalesOrderDetailsCommand
    {
    get;
    private set;
    }
#endregion Commands

private void SearchInSalesOrderDetails( string searchText)
{
MessageBox.Show(searchText);
}
public void SaveSalesOrderDetails()
{
CurrentSalesOrderDetails.ProductID = SelectedProduct.ProductID;
SalesOrderDetailsContext.SubmitChanges(OnCallbackSave, null);
}
private void OnCallbackSave(SubmitOperation p)
{
if (p.HasError)
{
p.MarkErrorAsHandled();
ErrorWindow.CreateNew(p.Error);
}
else
{
MessageBox.Show("SalesOrderDetails has been updated");
RaisePropertyChanged("SalesOrderDetailsCollection");
RaisePropertyChanged("CurrentSalesOrderDetails");
}
}

public static int CSalesOrderDetailID;
private void ObtainSalesOrderDetailID()
{

    string a = CurrentSalesOrderDetails.SalesOrderID.ToString();
    //int i = a.IndexOf(":") + 1;
    //a = a.Substring(i);
    int dashLoadPk;
    int.TryParse(a, out dashLoadPk);
    DashLoad_PK = dashLoadPk;
    CSalesOrderDetailID = dashLoadPk;
   // MessageBox.Show(DashLoad_PK.ToString());
}

private void EditCurrentInNewWindow()
    {
        ObtainSalesOrderDetailID();
        if (CSalesOrderDetailID > 0)
        {
            var frm = new ChildWindows.SalesOrderDetailCW();
            frm.Show();
            frm.Closed += new System.EventHandler(FrmClosed);
        }
    }

    void FrmClosed(object sender, System.EventArgs e)
    {
        LoadSalesOrderDetailsAsync();
    }

#region "Add New"
//http://forums.silverlight.net/forums/p/193377/449256.aspx
private void AddSalesOrderDetails()
{
    AdventureWorksLT.Web.Models.SalesOrderDetail salesOrderDetails = new AdventureWorksLT.Web.Models.SalesOrderDetail();
    SalesOrderDetailAddCW addNewWindow = new SalesOrderDetailAddCW();
    addNewWindow.DataContext = salesOrderDetails;
    addNewWindow.Closed += (s, ee) =>
    {
        if (addNewWindow.DialogResult == true)
        {
 
            SalesOrderDetailsContext.SalesOrderDetails.Add(salesOrderDetails);
            SalesOrderDetailsContext.SubmitChanges(p =>
            {
                if (p.HasError)
                {
                    p.MarkErrorAsHandled();
                    ErrorWindow.CreateNew(p.Error);
                }
                else
                {
                    MessageBox.Show("New SalesOrderDetails has been added");
                }
            }, null);
        }
    };
    addNewWindow.Show();
    addNewWindow.Closed += FrmClosedAdd;
}
void FrmClosedAdd(object sender, EventArgs e)
{
    LoadSalesOrderDetailsAsync();
}
#endregion "Add New"
private static int _dashload_PK;
public static int DashLoad_PK
{
get { return _dashload_PK; }
set { _dashload_PK = value ; }
}
private void ShowChartDashboard(object selectedItem)
{
//
string a = selectedItem.ToString();
int i = a.IndexOf(":") + 1;
a = a.Substring(i);
int dashLoadPk;
int.TryParse(a, out dashLoadPk);
DashLoad_PK = dashLoadPk;
Uri target = new Uri("/Customers/Pages/PatientsTitlePage?SalesOrderID=" + DashLoad_PK, UriKind.Relative);
var _theItem = selectedItem;
CurrentSalesOrderDetails = (SalesOrderDetail)_theItem;
//NavigationService.Navigate(target);
//var service = ((Page)((App)Application.Current).RootVisual).NavigationService;
//if (service != null) service.Navigate(target);
}
    
    private bool _isBusy;
    public bool IsBusy
    {
    get { return _isBusy; }
    set
    {
    _isBusy = value;
    RaisePropertyChanged("IsBusy");
    }
    }
    
    public string CurrentTime
    {
    get
    {
    DateTime time = DateTime.Now; 
    const string format = "MMM ddd d HH:mm yyyy"; 
    return (time.ToString(format));
    }
    }
    
       #region "Security"
        //Security methods
        private void CheckSecurity()
        {
            // Add code for LoggedIn and LoggedOut events
            WebContext.Current.Authentication.LoggedIn += Authentication_Changed;
            WebContext.Current.Authentication.LoggedOut += Authentication_Changed;
        }
        
        void Authentication_Changed(object sender, System.ServiceModel.DomainServices.Client.ApplicationServices.AuthenticationEventArgs e)
        {
            RaisePropertyChanged("IsAdmin");
        }
        
        private bool _IsAdmin;
        public bool IsAdmin
        {
            get { return CheckUserIsInRole("Admin"); }
        }
        
        private bool CheckUserIsInRole(string role)
        {
            return WebContext.Current.User.IsInRole(role);
        }
        
        //<HyperlinkButton x:Name="AdminLink" Visibility="{Binding IsAdmin,Converter={StaticResource BoolToVisibilityConverter},FallbackValue=Collapsed}" TargetName="ContentFrame" NavigateUri="/AdminView" Content="Admin" Style="{StaticResource LinkStyle}" />
        // CurrentUser is needed for logging
        public string CurrentUser
        {
        get { return WebContext.Current.User.ToString() ; }
        }
    
    #endregion "Security"
    
#region "LoadComboBoxData"

public EntitySet<Product> ProductCollection { get; set; }
private Product _selectedProduct;
public Product SelectedProduct
{
get { return _selectedProduct; }
set
{
_selectedProduct = value;
RaisePropertyChanged("SelectedProduct");
}
}
private long dtStart = 0;
private long dtEnd = 0;
void LoadComboBoxData()
{
dtStart = System.DateTime.Now.Ticks;

//ProductIDComboBox
_context = new AdventureWorksLTDomainContext();
_productQuery = _context.GetProductsQuery();
_productQuery = _productQuery.OrderBy(e => e.ProductID);
PerformAsyncQuery<Product>(_context, _productQuery, ProductIDComboBoxLoaded);
ProductCollection = _context.Products;
}


private void ProductIDComboBoxLoaded(object sender, AdventureWorksLT.Core.EntityResultsArgs<Product> e)
{
if (!e.HasError)
{
//SelectedProduct =
//ProductCollection.Where(c => c.ProductID == CurrentSalesOrderDetails.ProductID).SingleOrDefault();
SelectedProduct =
ProductCollection.FirstOrDefault();
}
}
private void SalesOrderDetailsLoadedComplete(object sender, AdventureWorksLT.Core.EntityResultsArgs<SalesOrderDetail> e)
{
IsBusy = false;
if (!e.HasError)
{
//SalesOrderDetailsCollection = SalesOrderDetailsContext.SalesOrderDetail;
SalesOrderDetailsCollection = new ObservableCollection<SalesOrderDetail>(SalesOrderDetailsContext.SalesOrderDetails.OrderBy(c => c.SalesOrderID).Take(20));
CurrentSalesOrderDetails = SalesOrderDetailsCollection.FirstOrDefault();
EnableCommands();
//SelectedProduct = ProductCollection.Where(c => c.ProductID == CurrentSalesOrderDetails.ProductID).SingleOrDefault();
SelectedProduct = ProductCollection.FirstOrDefault();
}
else
{
// notify user if there is any error
//AppMessages.RaiseErrorMessage.Send(e.Error);
}
}
private void AddNewForm_Closed(object sender, AdventureWorksLT.Core.EntityResultsArgs<SalesOrderDetail> e)
{
if (!e.HasError)
{
}
}
#endregion "LoadComboBoxData"
#region "Delete"
private bool _toDelete=false;
private void DeleteSalesOrderDetails()
{
_toDelete = true;
var salesOrderDetailsToDelete = CurrentSalesOrderDetails;
if (salesOrderDetailsToDelete != null)
{
var result = MessageBox.Show("Are you sure you wish to delete the Current SalesOrderDetails?", "Confirm Delete", MessageBoxButton.OKCancel);
if (result.Equals(MessageBoxResult.OK))
{
SalesOrderDetailsContext.SalesOrderDetails.Remove(salesOrderDetailsToDelete);
SalesOrderDetailsContext.SubmitChanges(o =>
{
if (o.HasError)
{
MessageBox.Show("Esta salesOrderDetails no se puede eliminar ya que existen datos que dependen de esta SalesOrderDetails.....", "Cancelado", MessageBoxButton.OKCancel);
o.MarkErrorAsHandled();
SalesOrderDetailsContext.RejectChanges();
}
else
{
MessageBox.Show("el registro de salesOrderDetails ha sido eliminado exitosamente ... ");
//LoadSalesOrderDetailsAsync();
RaisePropertyChanged("SalesOrderDetailsCollection");
CurrentSalesOrderDetails = SalesOrderDetailsCollection.FirstOrDefault();
}
}, null);
}
}
_toDelete = false;
}
#endregion "Delete"
#region "Print"
private void PrintSalesOrderDetails()
{
if (CurrentSalesOrderDetails != null)
{
PrintDocument document = new PrintDocument();
document.PrintPage += new System.EventHandler<PrintPageEventArgs>(document_PrintPage); // fires when every single page is going to print 
document.EndPrint += new System.EventHandler<EndPrintEventArgs>(document_EndPrint); // when printing is completed
string PrintQueue = "SalesOrderDetail_" + CurrentSalesOrderDetails.ToString(); // to show in the print queue
document.Print(PrintQueue); //fires when printing has begun
}
}
static void document_EndPrint(object sender, EndPrintEventArgs e)
{
if (e.Error != null)
{
ErrorWindow error = new ErrorWindow(e.Error.Message, e.Error.StackTrace);
}
else
MessageBox.Show("Print Complete");
}
void document_PrintPage(object sender, PrintPageEventArgs e)
{
PrintDocument document = sender as PrintDocument;
AdventureWorksLT.Web.Models.SalesOrderDetail appt = CurrentSalesOrderDetails as AdventureWorksLT.Web.Models.SalesOrderDetail;
if (appt != null)
{
//e.HasMorePages = appt.ChildEntity != null && document.PrintedPageCount < appt.ChildEntity.Count;
//if (document.PrintedPageCount > 0)
//{
// e.PageVisual = new ChildEntityFReport() { DataContext = appt.ChildEntity.ElementAt(document.PrintedPageCount - 1) };
//}
//else


//e.PageVisual = new SalesOrderDetailFReport() { DataContext = appt };
}
}
#endregion "Print"
}
}
